/**
 * 
 */
package com.quanyan.place.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.TbBizPlaceOrder;
import com.quanyan.place.entity.TbBizPlaceOrderExample;
import com.quanyan.place.entity.TbBizPlaceOrderItem;
import com.quanyan.place.entity.TbBizPlacePayItem;
import com.quanyan.place.enums.PayTypeEnum;
import com.quanyan.place.mapper.TbBizPlaceGoodsMapper;
import com.quanyan.place.mapper.TbBizPlaceMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderItemMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderMapper;
import com.quanyan.place.mapper.TbBizPlacePayItemMapper;

/**
 * 银联pos改价支付，重新生成订单 （主要针对开单散客付款、门票散客支付、商品售卖散客支付）
 * 
 * @author tim
 * @time 2017年3月31日
 *
 */
public class PosChangePriceServiceImpl {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	TbBizPlaceGoodsMapper tbBizPlaceGoodsMapper;

	@Autowired
	TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

	@Autowired
	TbBizPlaceMapper tbBizPlaceMapper;

	@Autowired
	TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

	@Autowired
	TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

	@Autowired
	IBaseService iBaseService;
	
	/**
	 * 生成散客商品订单
	 * 
	 * @return
	 */
	public TbBizPlaceOrder generateGoodsOrder(TbBizPlaceOrder oldOrder,List<TbBizPlaceOrderItem> placeOrderItems,Integer adminPayType,BigDecimal payAmount,String oldPlaceOrderId) {

		String placeNewOrderId = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM,oldOrder.getCreateUid());
		logger.info("重新生单，旧订单号为:placeOrderId="+oldPlaceOrderId+",新订单号为:placeOrderId="+placeNewOrderId);
		for (TbBizPlaceOrderItem req : placeOrderItems) {
			req.setPlaceOrderId(placeNewOrderId);
			tbBizPlaceOrderItemMapper.insert(req);
		}
		
		 //copy原先订单数据到新订单，并修改部分数据
  		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
  		org.springframework.beans.BeanUtils.copyProperties(oldOrder, newTbBizPlaceOrder);
  		newTbBizPlaceOrder.setPlaceOrderId(placeNewOrderId);
  		newTbBizPlaceOrder.setHandAdjustAmount(org.springframework.util.StringUtils.isEmpty(oldOrder.getHandAdjustAmount())?BigDecimal.ZERO:oldOrder.getHandAdjustAmount().subtract(payAmount));
  		newTbBizPlaceOrder.setCreateTime(new Date());//重新生单，订单创建时间变了
		
		tbBizPlaceOrderMapper.insertSelective(newTbBizPlaceOrder);
		logger.debug("========================插入商品订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(newTbBizPlaceOrder));

		// 插入支付明细
		if (!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
			TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
			tbBizPlacePayItem.setPlaceOrderId(placeNewOrderId);
			// 实付金额不为空，则明细支付插入实付金额
			tbBizPlacePayItem.setAmount(payAmount);
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
			tbBizPlacePayItem.setPayType(adminPayType);
			tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			tbBizPlacePayItemMapper.insert(tbBizPlacePayItem);
			logger.debug("========================插入商品订单支付数据:TbBizPlacePayItem:{}", JSON.toJSONString(tbBizPlacePayItem));
		}
		this.cancelOrder(oldPlaceOrderId);
		return newTbBizPlaceOrder;
	}

	
	/**
	 * 生成散客门票订单
	 * @return
	 */
	public TbBizPlaceOrder generateTicketOrder(TbBizPlaceOrder oldOrder, List<TbBizPlaceOrderItem> tbBizPlaceOrderItemsNotMember,Integer adminPayType,BigDecimal payAmount,String oldPlaceOrderId){
		String placeNewOrderId = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM,oldOrder.getCreateUid());
		logger.info("重新生单，旧订单号为:placeOrderId="+oldPlaceOrderId+",新订单号为:placeOrderId="+placeNewOrderId);
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItemsNotMember) {
            if (null != item.getTicketCount() && null != item.getSalePrice()){
                //插入明细
                item.setPlaceOrderId(placeNewOrderId);
                tbBizPlaceOrderItemMapper.insert(item);
            }
        }
       
        //copy原先订单数据到新订单，并修改部分数据
  		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
  		org.springframework.beans.BeanUtils.copyProperties(oldOrder, newTbBizPlaceOrder);
  		newTbBizPlaceOrder.setPlaceOrderId(placeNewOrderId);
  		newTbBizPlaceOrder.setHandAdjustAmount(org.springframework.util.StringUtils.isEmpty(oldOrder.getHandAdjustAmount())?BigDecimal.ZERO:oldOrder.getHandAdjustAmount().subtract(payAmount));
  		newTbBizPlaceOrder.setCreateTime(new Date());//重新生单，订单创建时间变了

        if (this.tbBizPlaceOrderMapper.insertSelective(newTbBizPlaceOrder) == 0) {
            logger.debug("插入门票订单失败");
        }
        
        //pos删除下单生成支付明细，支付成功生成支付明细
		if (!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
			TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
			tbBizPlacePayItem.setPlaceOrderId(placeNewOrderId);
			tbBizPlacePayItem.setAmount(payAmount);
			tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
			tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
			tbBizPlacePayItem.setPayType(adminPayType);

			if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) == 0) {
				logger.debug("插入门票支付明细失败");
			}
		}
     
        this.cancelOrder(oldPlaceOrderId);	
        return newTbBizPlaceOrder;
    
	}
	
	/**
	 * 生成散客开单订单
	 * @return
	 */
	public TbBizPlaceOrder generatePlaceBillingOrder(TbBizPlaceOrder oldOrder,List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,Integer adminPayType,BigDecimal payAmount,String oldPlaceOrderId){
		String placeNewOrderId = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM,oldOrder.getCreateUid());
		logger.info("重新生单，旧订单号为:placeOrderId="+oldPlaceOrderId+",新订单号为:placeOrderId="+placeNewOrderId);
		//售卖总价格
		List<TbBizPlaceOrderItem> newOrderItems=new ArrayList<>();
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			item.setPlaceOrderId(placeNewOrderId);
			newOrderItems.add(item);//原先订数据copy,出placeOrderId变更
			tbBizPlaceOrderItemMapper.insertSelective(item);
		}
		
		//copy原先订单数据到新订单，并修改部分数据
		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
		org.springframework.beans.BeanUtils.copyProperties(oldOrder, newTbBizPlaceOrder);
		newTbBizPlaceOrder.setPlaceOrderId(placeNewOrderId);
		newTbBizPlaceOrder.setHandAdjustAmount(org.springframework.util.StringUtils.isEmpty(oldOrder.getHandAdjustAmount())?BigDecimal.ZERO:oldOrder.getHandAdjustAmount().subtract(payAmount));
		newTbBizPlaceOrder.setCreateTime(new Date());//重新生单，订单创建时间变了

		if (this.tbBizPlaceOrderMapper.insertSelective(newTbBizPlaceOrder) != 0) {
			logger.debug("========================插入散客开单订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(newTbBizPlaceOrder));
			if (!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
				TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
				tbBizPlacePayItem.setPlaceOrderId(placeNewOrderId);
				tbBizPlacePayItem.setAmount(payAmount);
				tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
				tbBizPlacePayItem.setPayType(adminPayType);
				tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
				if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) != 0) {
					logger.debug("========================插入散客开单订单支付数据:TbBizPlacePayItem:{}",
							JSON.toJSONString(tbBizPlacePayItem));


				}
			}
			//把原先的订单里面的销售计划状态改为未预定状态
			iBaseService.placeBillingUpdatePlaceUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_PREORDER_STATUS);
			
			//把新生成的订单里面的销售计划状态改为锁定状态
			iBaseService.placeBillingUpdatePlaceUnitSalePlan(newOrderItems,PlaceConstants.PLACE_LOCk_STATUS);
			//取消原先订单
			this.cancelOrder(oldPlaceOrderId);
		}

		return newTbBizPlaceOrder;
	}
	
	/**
	 * 生成包场订单
	 * @return
	 */
	public TbBizPlaceOrder generatePlaceBookAllOrder(TbBizPlaceOrder oldOrder,List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,Integer adminPayType,BigDecimal payAmount,String oldPlaceOrderId){
		String placeNewOrderId = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM,oldOrder.getCreateUid());
		logger.info("重新生单，旧订单号为:placeOrderId="+oldPlaceOrderId+",新订单号为:placeOrderId="+placeNewOrderId);
		//售卖总价格
		for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems) {
			item.setPlaceOrderId(placeNewOrderId);
			tbBizPlaceOrderItemMapper.insertSelective(item);
		}
		
		//copy原先订单数据到新订单，并修改部分数据
		TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
		org.springframework.beans.BeanUtils.copyProperties(oldOrder, newTbBizPlaceOrder);
		newTbBizPlaceOrder.setPlaceOrderId(placeNewOrderId);
		newTbBizPlaceOrder.setHandAdjustAmount(org.springframework.util.StringUtils.isEmpty(oldOrder.getHandAdjustAmount())?BigDecimal.ZERO:oldOrder.getHandAdjustAmount().subtract(payAmount));
		newTbBizPlaceOrder.setCreateTime(new Date());//重新生单，订单创建时间变了
		if (this.tbBizPlaceOrderMapper.insertSelective(newTbBizPlaceOrder) != 0) {
			logger.debug("========================插入包场订单数据:TbBizPlaceOrder:{}", JSON.toJSONString(newTbBizPlaceOrder));
			if (!PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY.equals(adminPayType.toString())){
				TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
				tbBizPlacePayItem.setPlaceOrderId(placeNewOrderId);
				tbBizPlacePayItem.setAmount(payAmount);
				tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
				tbBizPlacePayItem.setPayType(adminPayType);
				tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
				if (tbBizPlacePayItemMapper.insertSelective(tbBizPlacePayItem) != 0) {
					logger.debug("========================插入包场订单支付数据:TbBizPlacePayItem:{}",
							JSON.toJSONString(tbBizPlacePayItem));
				}
			}
			
			//取消原先订单
			this.cancelOrder(oldPlaceOrderId);
		}

		return newTbBizPlaceOrder;
	}
	
	/**
	 * 重新生成新订单，取消原先未支付订单
	 * @param placeOrderId
	 */
	private void cancelOrder(String placeOrderId){
		TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
		tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
		List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
		if(!com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceOrders)){
			for(TbBizPlaceOrder placeOrder:tbBizPlaceOrders){
				TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
				org.springframework.beans.BeanUtils.copyProperties(placeOrder, newTbBizPlaceOrder);
				newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
				newTbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
				newTbBizPlaceOrder.setIsEffective(PlaceConstants.IS_ORDER_EFFECTIVE_NO);//设置订单无效
				newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
				if(this.tbBizPlaceOrderMapper.updateByPrimaryKeySelective(newTbBizPlaceOrder) != 0){
					logger.info("重新生成新订单，取消原先未支付订单成功！");
				}
			}
			
			
			
		}
		
			
		}
			
		
			
		
	
}
